package flex.cc.medical.service.impl;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import flex.cc.common.utils.CommonUtils;
import flex.cc.core.utils.RequestUtil;
import flex.cc.medical.service.MedicalService;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dto.entity.CouponTrackEntity;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.store.service.CouponTrackService;
import flex.cc.store.service.StoreCouponService;
import flex.cc.util.APIConfigUtil;

/**
 * @author wkangle
 * @className MedicalServiceImpl
 * @description C端医护类服务service层
 * @time 2022-02-08 10:49:48
 */
@Service("medicalService")
public class MedicalServiceImpl implements MedicalService {

    private static final Logger logger = LoggerFactory.getLogger(MedicalServiceImpl.class);

//    @Value("${api.config.appCode}")
//    private String appCode;

    @Resource
    private StoreCouponService storeCouponService;
    @Resource
    private CouponTrackService couponTrackService;
    @Autowired
    private StoreCouponDao storeCouponDao;
    @Autowired
    private APIConfigUtil apiConfigUtil;

    /**
     * @param params 请求参数
     * @return
     * @description 请求医护合作方参数加密
     * @author wkangle
     * @time 2022-02-08 10:48:22
     * @exception/throws
     */
    @Override
    public Map<String, String> initEncrypt(Map<String, Object> params) {
        Map<String, String> result = new HashMap<>();
        //激活码  通过激活码获取数据库中维护的appCode
        String activateCode = (String) params.get("activateCode");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("activateCode", activateCode);
		StoreCouponEntity couponEntity = storeCouponDao.getOneByParams(paramMap);
		String provider = couponEntity.getServer();
		
		String appCode = apiConfigUtil.getApiConfig(provider, "medical_code");
		String yhRedirectUrl = apiConfigUtil.getApiConfig(provider, "medical_redirect");
		
		logger.info("请求医护合作方跳转url ==" + yhRedirectUrl);
		
        params.put("appCode", appCode);
        String jsonString = CommonUtils.toJSONString(params);
        String encode = Base64.getEncoder().encodeToString(jsonString.getBytes());

        logger.info("加密后参数--- {}", encode);
        result.put("code", "0000");
        result.put("redirectUrl", yhRedirectUrl + "?params=" + encode);
        logger.info("RedirectUrl ==> " + yhRedirectUrl + "?params=" + encode);
        return result;
    }

    /**
     * @param params 请求参数
     * @return
     * @description 注册兑换
     * @author wkangle
     * @time 2022-02-08 10:48:22
     * @exception/throws
     */
    @Override
    public Map<String, String> activating(Map<String, Object> params) {
        Map<String, String> result = new HashMap<>();
        String couponNum = params.get("couponNum") != null ? params.get("couponNum").toString() : null;
        if (couponNum == null) {
            result.put("code", "0001");
            result.put("message", "卡券码为空！");
            return result;
        }
        StoreCouponEntity storeCouponEntity = storeCouponService.queryByCouponNum(couponNum);
        String userCode = RequestUtil.getLoginUser().getUserCode();
        if (storeCouponEntity != null) {
            Map<String, Object> updateParams = new HashMap<>();
            updateParams.put("couponNum", couponNum);
            updateParams.put("packageCode", params.get("packageCode") != null ? params.get("packageCode").toString() : null);
            updateParams.put("isActivate", 1); // 医护类卡券是否已激活，默认0-否，1-是
            updateParams.put("updateTime", new Date());
            updateParams.put("updater", userCode);
            int i = storeCouponService.updateByParam(updateParams);
            // 记录轨迹
            if (i == 1) {
                saveTrack(storeCouponEntity, "0", "医护类卡券兑换激活成功", "1", userCode);
                result.put("code", "0000");
                result.put("message", "success");
                return result;
            } else {
                saveTrack(storeCouponEntity, "0", "医护类卡券兑换激活失败", "0", userCode);
                result.put("code", "0001");
                result.put("message", "注册兑换失败\n(卡券码: " + couponNum + ")，请联系管理员");
                return result;
            }
        } else {
            logger.info(System.currentTimeMillis() + " ==> 医护类卡券兑换激活失败: 系统中找不到对应卡券(卡券码: {})", couponNum);
            result.put("code", "0001");
            result.put("message", "系统中找不到对应卡券\n(卡券码: " + couponNum + ")");
            return result;
        }
    }

    //trackType-轨迹类型：0-车服内部，1-与上游交互，2-与下游交互，3-与商户端交互
    public void saveTrack(StoreCouponEntity couponEntity, String trackType, String trackDesc, String result, String creater) {
        Date d = new Date();
        CouponTrackEntity vo = new CouponTrackEntity(couponEntity.getId(), couponEntity.getCouponNum(),
                trackType, trackDesc, couponEntity.getStatus(), result);
        vo.setIsDelete(0);
        vo.setCreateTime(d);
        vo.setCreater(creater);
        vo.setUpdateTime(d);
        vo.setUpdater(creater);
        couponTrackService.insert(vo);
    }

}
